//
//  Extension+UIImage.swift
//  SHWeibo
//
//  Created by jingming wang on 16/8/4.
//  Copyright © 2016年 cpy.name. All rights reserved.
//

import UIKit

extension UIImage {
    //MARK: - 获取截屏图片
    class func getScreenShot() -> UIImage {
        // 获取window
        let window = UIApplication.sharedApplication().keyWindow!
        
        // 开启上下文
        UIGraphicsBeginImageContext(window.bounds.size)
        // 将window渲染到上下文中
        window.drawViewHierarchyInRect(window.bounds, afterScreenUpdates: false)
        // 从上下文中获取image
        let image = UIGraphicsGetImageFromCurrentImageContext()
        // 关闭上下文
        UIGraphicsEndImageContext()
        
        return image
    }
    // MARK: - 压缩图片
    func getScaledImage(expectedWidth:CGFloat) -> UIImage {
        // 如果图片宽度 小于指定的宽度 直接返回原始图片
        if self.size.width < expectedWidth {
            return self
        }
        // 获取期望的高度
        let expectedHeight = (expectedWidth*self.size.height)/self.size.width
        let rect = CGRect(x: 0, y: 0, width: expectedWidth, height: expectedHeight)
        // 开启上下文
        UIGraphicsBeginImageContext(rect.size)
        // 将图片渲染到上下文中
        drawInRect(rect)
        // 从上下文中获取image
        let image = UIGraphicsGetImageFromCurrentImageContext()
        // 关闭上下文
        UIGraphicsEndImageContext()
        return image
    }
    
    // MARK: - 获取emoticon的image
    class func getEmoticonImage(path: String?) -> UIImage? {
        return UIImage(named: path ?? "", inBundle: emoticonBundle, compatibleWithTraitCollection: nil)
    }
    
}